﻿using System.IO.Compression;
using System.IO;
using System.Text;
using System;

namespace CoreShop.Library.Units
{
    public class BrotliDecompressor
    {
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="base64Data"></param>
        /// <returns></returns>
        public static string Decompress(string base64CompressedString, Encoding encoding = null)
        {
            try
            {
                // 将Base64字符串转换为字节数组
                byte[] compressedBytes = Convert.FromBase64String(base64CompressedString);

                // 使用内存流解压
                using (MemoryStream compressedStream = new MemoryStream(compressedBytes))
                {
                    using (GZipStream decompressionStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                    {
                        using (MemoryStream decompressedStream = new MemoryStream())
                        {
                            byte[] buffer = new byte[8192];
                            int bytesRead;
                            while ((bytesRead = decompressionStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                decompressedStream.Write(buffer, 0, bytesRead);
                            }

                            // 将解压后的字节数组转换为字符串
                            return encoding.GetString(decompressedStream.ToArray());
                        }
                    }
                }
            }
            catch (FormatException ex)
            {
                Console.WriteLine($"Base64格式错误: {ex.Message}");
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"解压失败: {ex.Message}");
                return null;
            }
        }
        public static string Compress(string data, int quality = 6)
        {
            // 将字符串转为UTF-8字节数组
            byte[] input = Encoding.UTF8.GetBytes(data);

            //using (MemoryStream outputStream = new MemoryStream())
            //{
            //    // 设置压缩质量（0-11），数值越大压缩率越高但速度越慢
            //    var options = new BrotliEncoderOptions { Quality = quality };

            //    using (BrotliStream brotliStream = new BrotliStream(outputStream, CompressionMode.Compress, options))
            //    {
            //        brotliStream.Write(input, 0, input.Length);
            //    }

            //    // 使用Base64编码以便Java处理
            //    return Convert.ToBase64String(outputStream.ToArray());
            //}

            return data;
        }

    }
}
